package cn.kgc.mybatis.web.service.impl;

import cn.kgc.mybatis.web.dto.EmpPageDTO;
import cn.kgc.mybatis.web.entity.Emp;
import cn.kgc.mybatis.web.mapper.EmpMapper;
import cn.kgc.mybatis.web.service.EmpService;
import cn.kgc.mybatis.web.utils.MybatisUtil;
import cn.kgc.mybatis.web.utils.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.HashMap;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/1/29
 * @description
 */
public class EmpServiceImpl implements EmpService {

    private EmpMapper empMapper = MybatisUtil.getMapperProxy(EmpMapper.class);

    @Override
    public ResponseResult addEmp(Emp emp) {

        ResponseResult responseResult = new ResponseResult();
        try {
            Integer line = empMapper.insertEmp(emp);
            // 添加成功
            responseResult.setCode(200);
            responseResult.setMessage("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            // 添加失败
            responseResult.setCode(110);
            responseResult.setMessage("添加失败");
        }

        return responseResult;
    }

    @Override
    public ResponseResult searchEmp(EmpPageDTO empPageDTO) {

        ResponseResult responseResult = new ResponseResult();

        PageHelper.startPage(empPageDTO.getCurrentPage(), empPageDTO.getSize());
        List<Emp> emps = empMapper.searchEmp(empPageDTO.getEname(), empPageDTO.getAge());
        PageInfo<Emp> empPageInfo = new PageInfo<>(emps);
        long total = empPageInfo.getTotal();
        List<Emp> list = empPageInfo.getList();

        responseResult.setCode(200);
        responseResult.setMessage("查询成功");
        HashMap<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("pageData", list);
        responseResult.setData(result);

        return responseResult;
    }

    @Override
    public ResponseResult editEmp(Emp emp) {

        ResponseResult responseResult = new ResponseResult();
        try {
            empMapper.updateEmp(emp);
            responseResult.setCode(200);
            responseResult.setMessage("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode(110);
            responseResult.setMessage("更新失败");
        }

        return responseResult;
    }

    @Override
    public ResponseResult batchDelete(List<String> list) {

        ResponseResult responseResult = new ResponseResult();

        try {
            empMapper.batchDelete(list);
            responseResult.setCode(200);
            responseResult.setMessage("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            responseResult.setCode(110);
            responseResult.setMessage("删除失败");
        }

        return  responseResult;
    }
}
